from django.http import HttpResponseRedirect
from django.views.generic.list_detail import object_list
from django.views.generic.date_based import archive_month
from django.views.generic.simple import direct_to_template
from django.contrib.contenttypes.models import ContentType

from biologeek.journal.models import Post
from biologeek.bistrot.models import Thought
from biologeek.tagging.models import Tag, TaggedItem

def view_tag(request, tags):
    tag_list = [Tag.objects.get(name=tag) for tag in tags.split(',')]
    post_list = TaggedItem.objects.get_by_model(Post, tag_list)
    if len(post_list) > 1:
        ctype = ContentType.objects.get_for_model(Post)
        related_tags = Tag.objects.filter(items__object_id__in=[s.id for s in post_list]).filter(items__content_type__pk=ctype.id).exclude(items__tag__in=tag_list).distinct()
    else:
        related_tags = []
    return object_list(request,
        queryset=post_list,
        template_name='journal/post_list_for_tag.html',
        extra_context={ 'tag_list': tag_list, 'related_tags': related_tags },
        template_object_name='post')

def add_tag(request, tags, tag):
    """ Allow tag addition with a plus in url, useful for chained tags.

    Usage::

        /django/+python redirect to /django,python/
    """
    if tag not in tags and tag.startswith('+'):
        return HttpResponseRedirect('/%s,%s/' % (tags, tag[1:].lower()))
    else:
        return HttpResponseRedirect('/%s/' % (tags, ))

def redirect_to_archives(request, year):
    return HttpResponseRedirect('/archives/?highlight=%s' % year)

def archives(request):
    return direct_to_template(request, 'archives.html',
        {
            'post_list':Post.published.all(),
            'thought_list':Thought.published.all(),

        }
    )

def archives_month(request, year, month):
    import time, datetime
    try:
        date = datetime.date(*time.strptime(year+month, '%Y%m')[:3])

        # Calculate first and last day of month, for use in a date-range lookup.
        first_day = date.replace(day=1)
        if first_day.month == 12:
            last_day = first_day.replace(year=first_day.year + 1, month=1)
        else:
            last_day = first_day.replace(month=first_day.month + 1)
        thought_list = Thought.published.filter(publication_date__range=(first_day, last_day))
    except ValueError:
        thought_list = None

    return archive_month(request, year, month, Post.published.all(),
        'publication_date',
        template_object_name = 'post',
        month_format = '%m',
        allow_empty = True,
        extra_context={ 'thought_list': thought_list }
    )
